<template>
  <div class="echartsContainer">
    <div
      class="echartsHeader"
      style="display: flex; justify-content: flex-start; align-items: center"
    >
      <!-- 数值与信号图表不同显示 -->
      <div>
        <el-radio-group v-model="radio1" @change="changeDiffWayShowData">
          <el-radio label="数值图表" border>数值表</el-radio>
          <el-radio label="信号图表" border>信号表</el-radio>
        </el-radio-group>
      </div>
      <!-- echarts显示选择切换 -->
      <div v-if="state.doubleShow" style="margin-left: 30px">
        <el-checkbox v-model="state.numberShow" label="数值显示" border />
        <el-checkbox v-model="state.mergeShow" label="合并显示" border />
      </div>
      <!-- 数值图表字段显示 -->
      <div class="grid" v-if="state.doubleShow">
        <el-dropdown :max-height="380" :hide-on-click="false">
          <el-button class="table-search-button-item" color="#dcdfe6" plain>
            <el-icon>
              <Grid style="color: black" />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(item, idx) in realTime.DefaultFields"
                :key="idx"
              >
                <el-checkbox
                  @change="onChangeShowColumn($event, item.dictValue!)"
                  :model-value="item.remark == 'double'"
                  size="small"
                  :label="item.dictLabel"
                />
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- 信号图表字段显示 -->
      <!-- <div></div> -->
    </div>
    <div v-if="state.doubleShow" class="showEchartContainer">
      <el-scrollbar height="60vh">
        <div
          class="content"
          v-for="(item, idx) in realTime.DefaultFields"
          :key="idx"
        >
          <div
            v-if="item.remark == 'double'"
            class="valueEcharts"
            ref="echartsRef"
            :id="'myChart' + item.dictValue"
          ></div>
        </div>
      </el-scrollbar>
    </div>
    <div v-else ref="" class="showEchart"></div>
  </div>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { reactive, ref, onMounted, inject } from "vue";
import { timeFormat } from "@/utils/common";
import { useRoute } from "vue-router";
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TitleComponentOption,
  ToolboxComponent,
  ToolboxComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  LegendComponent,
  LegendComponentOption,
  BrushComponent,
  BrushComponentOption,
  MarkAreaComponent,
  MarkAreaComponentOption,
  VisualMapComponent,
  VisualMapComponentOption,
  CalendarComponent,
  CalendarComponentOption,
  DataZoomComponent,
  DataZoomComponentOption,
} from "echarts/components";
import {
  LineChart,
  LineSeriesOption,
  ScatterChart,
  ScatterSeriesOption,
  HeatmapChart,
  HeatmapSeriesOption,
} from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
import { dirxml } from "console";
echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  ScatterChart,
  CanvasRenderer,
  UniversalTransition,
  BrushComponent,
  MarkAreaComponent,
  VisualMapComponent,
  HeatmapChart,
  CalendarComponent,
  DataZoomComponent,
]);
type EChartsOption = echarts.ComposeOption<
  | TitleComponentOption
  | ToolboxComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | LegendComponentOption
  | LineSeriesOption
  | BrushComponentOption
  | MarkAreaComponentOption
  | ScatterSeriesOption
  | VisualMapComponentOption
  | HeatmapSeriesOption
  | CalendarComponentOption
  | DataZoomComponentOption
>;
const itemObject = inject("itemObject") as any;
const config = inject("config") as any;
const realTime = inject("realTime") as any;
const route = useRoute();

const radio1 = ref("数值图表");

const deviceEchartRef = ref<HTMLDivElement>(); //获取图表展示的dom 基础数据折现图

const state: {
  charts: any[];
  rightNow: string;
  rightHour: any;
  rightMinute: any;
  doubleShow: boolean;
  numberShow: boolean;
  mergeShow: boolean;
} = reactive({
  charts: [],
  rightNow: "",
  rightHour: "",
  rightMinute: "",
  doubleShow: true,
  numberShow: false,
  mergeShow: false,
});

const Fileds: {
  defaultFileds: any[]; //默认内循环温度
  filedsData: any; //遍历出来的字段数组
  optionsSeries: any[]; //折线图实际数据
  optionsLegendData: any[]; //折线图legen标识
  customOptions: any; //自定义折线图配置
  optionNull: any; //折线图非数据占位
  optionNullTwo: any; //折线图无数据占位
} = reactive({
  defaultFileds: [],
  filedsData: {},
  optionsSeries: [],
  optionsLegendData: [],
  customOptions: {
    // color: ["#5470c6", "#91cc75", "#ee6666"],
    backgroundColor: "transparent",
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: [],
      textStyle: {},
      top: "3%",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: "none",
        },
        restore: {},
        saveAsImage: {},
      },
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      // data: periodOfTime(state.rightHour - 0, state.rightMinute - 0),
      data: [],
      // axisLabel: {
      //   interval: 5, // 设置数据间隔
      //   // rotate: -38, // 标题倾斜
      // },
    },
    yAxis: {
      type: "value",
      boundaryGap: [0, "100%"],
      name: "",
      axisLabel: {
        interval: 5, // 设置数据间隔
        // rotate: -38, // 标题倾斜
      },
      // max: 20, // 这里将Y轴的最大值设为100
    },
    dataZoom: [
      {
        type: "slider", // 内置型数据区域缩放组件
        xAxisIndex: 0, // 设置对哪个 x 轴进行缩放
        start: 0, // 数据窗口范围的起始百分比
        end: 100, // 数据窗口范围的结束百分比
      },
      {
        type: "slider", // 滑动条型数据区域缩放组件
        yAxisIndex: 0, // 设置对哪个 x 轴进行缩放
        start: 0, // 数据窗口范围的起始百分比
        end: 100, // 数据窗口范围的结束百分比
        // bottom: 10, // 滑动条组件距离底部的距离
      },
    ],
    series: [],
  },
  optionNull: {
    backgroundColor: "transparent",
    title: {
      text: "无法使用图表展示，请切换为数据",
      x: "center",
      y: "center",
      textStyle: {
        fontWeight: "normal",
        fontSize: 16,
      },
    },
  },
  optionNullTwo: {
    backgroundColor: "transparent",
    title: {
      text: "暂无数据",
      x: "center",
      y: "center",
      textStyle: {
        fontWeight: "normal",
        fontSize: 16,
      },
    },
  },
});

//获取当前时间
const getTime = () => {
  let arr = timeFormat("", "hh:MM").split(":");
  state.rightHour = arr[0];
  state.rightMinute = arr[1];
  console.log("获取当前时间", state.rightHour, state.rightMinute);
};
getTime();

//选择不同方法展示数据
const changeDiffWayShowData = (value: any) => {
  console.log("选择不同方法展示数据", value);
  switch (value) {
    case "数值图表":
      state.doubleShow = true;
      break;
    case "信号图表":
      state.doubleShow = false;
      break;
  }
};

const onChangeShowColumn = (
  value: string | number | boolean,
  field: string
) => {
  console.log("选择字段", value, field);
};

//生成自定义折线图
const initCustom = () => {
  const paramsChart = config.layout.isDark
    ? echarts.init(deviceEchartRef.value as HTMLDivElement, "dark")
    : echarts.init(deviceEchartRef.value as HTMLDivElement);
  let options = Fileds.customOptions;
  console.log("生成自定义折线图", options);

  paramsChart.setOption(options);
  state.charts.push(paramsChart);
};
//非数据使用占位图表
const initNull = () => {
  const paramsChart = config.layout.isDark
    ? echarts.init(deviceEchartRef.value as HTMLDivElement, "dark")
    : echarts.init(deviceEchartRef.value as HTMLDivElement);
  let options = Fileds.optionNull;
  console.log("无数据使用占位图表", options);

  paramsChart.setOption(options);
  state.charts.push(paramsChart);
};
//无数据使用占位图表
const initNullTwo = () => {
  const paramsChart = config.layout.isDark
    ? echarts.init(deviceEchartRef.value as HTMLDivElement, "dark")
    : echarts.init(deviceEchartRef.value as HTMLDivElement);
  let options = Fileds.optionNullTwo;
  console.log("无数据使用占位图表", options);

  paramsChart.setOption(options);
  state.charts.push(paramsChart);
};

//取出当前类别字段
const showFileds = (val: string) => {
  dShift(); //释放图表
  let tempArr = [];
  let len = itemObject.fullData.length;
  for (let i = 0; i < len; i++) {
    let temObj = {
      label: "",
      prop: "",
      align: "center",
      unit: "",
    };
    if (itemObject.fullData[i].categoryName == val) {
      //判断该字段使用卧式机柜名称还是立式机柜名称
      temObj.label =
        realTime.realTimetype === "卧式"
          ? itemObject.fullData[i].objectName
          : itemObject.fullData[i].objectNameVertical;
      temObj.prop = itemObject.fullData[i].mqttFiled;
      temObj.unit = itemObject.fullData[i].unit;
      tempArr.push(temObj);
    }
  }
  Fileds.defaultFileds = tempArr;
  getDiffFiledsData(Fileds.defaultFileds); //遍历字段组数据
};

//获取告警类别备注判断是否图表展示
const isEcharts = (val: string) => {
  return realTime.typeCategoryFormat[val] == "long" ? true : false;
};
//生成自定义图表数据
const getDiffFiledsData = (fileds: any[]) => {
  if (!isEcharts(realTime.history)) {
    //非int数据不用图表展示
    initNull();
    return;
  }
  let originObj = {
    name: "槽体内液体温度T1",
    type: "line",
    stack: "Total",
    data: [],
    markPoint: {
      data: [
        { type: "max", name: "Max" },
        { type: "min", name: "Min" },
      ],
    },
  };
  let newArrLegendData = []; //字段数据
  let newOptionsSeries = [];
  for (let i = 0, len = fileds.length; i < len; i++) {
    let temp = _.cloneDeep(originObj);
    temp.name = fileds[i].label + fileds[i].prop;
    temp.data = realTime.endData[fileds[i].prop];
    temp.stack = "Total" + i; //关于Echarts多条折线图堆叠折线绘制错误问题

    newOptionsSeries.push(temp);
    newArrLegendData.push(temp.name);
  }
  Fileds.optionsSeries = newOptionsSeries;
  Fileds.optionsLegendData = newArrLegendData;
  Fileds.customOptions.yAxis.name = Fileds.defaultFileds[0].unit;
  Fileds.customOptions.series = newOptionsSeries; //主要数据
  Fileds.customOptions.legend.data = newArrLegendData; //legend标识数据
  Fileds.customOptions.xAxis.data = realTime.xAxisData;
  initCustom(); //初始化自定义图表
  console.log(
    "生成自定义图表数据",
    newOptionsSeries,
    newArrLegendData,
    Fileds.optionsSeries,
    Fileds.optionsLegendData
  );
};

const getDiffFileds = (filed: string) => {
  showFileds(filed); //取出字段组数据
};

//默认获取当前时间段数据
const getTimePeriodOfDeviceData = () => {
  realTime
    .getElectricDataEcharts({
      pageSize: 9999999,
      deviceId: route.query.deviceId,
      params: {
        beginTime: realTime.beginTime,
        endTime: realTime.endTime,
      },
    })
    .then((res: any) => {});
};

onMounted(() => {
  console.log("历史数据默认字段", realTime.DefaultFields, realTime.tags);
  getTimePeriodOfDeviceData(); //默认获取当前时间段数据
});

//释放state中图表并删除
const dShift = () => {
  return new Promise((resolve, reject) => {
    for (const key in state.charts) {
      state.charts[key].dispose();
    }
    resolve("");
  });
};
</script>
<style lang="scss" scoped>
.echartsContainer {
  width: 100%;
  height: 65vh;
  margin: 0 auto;
  .echartsHeader {
    position: relative;
    .grid {
      position: absolute;
      right: 0;
    }
  }
  .showEchartContainer {
    margin: 0 auto;
    width: 95%;
    .content {
      width: 100%;
      .valueEcharts {
        width: 100%;
        height: 300px;
      }
    }
  }
}
</style>
